package app

import (
	"context"

	"github.com/CIPFZ/collector/internal/config"

	"go.uber.org/zap"
)

// Collector 主应用程序结构
type Collector struct {
	logger *zap.Logger
	config *config.Config
	ctx    context.Context
	cancel context.CancelFunc
	debug  bool
}

// NewCollector 创建新的 Collector 实例
func NewCollector(logger *zap.Logger, config *config.Config) *Collector {
	ctx, cancel := context.WithCancel(context.Background())

	return &Collector{
		logger: logger,
		config: config,
		ctx:    ctx,
		cancel: cancel,
	}
}

// Context 返回应用上下文
func (c *Collector) Context() context.Context {
	return c.ctx
}

// Cancel 取消应用上下文
func (c *Collector) Cancel() {
	c.cancel()
}

// Logger 返回日志器
func (c *Collector) Logger() *zap.Logger {
	return c.logger
}

// Config 返回配置
func (c *Collector) Config() *config.Config {
	return c.config
}

// Shutdown 优雅关闭
func (c *Collector) Shutdown() error {
	c.logger.Info("Shutting down collector...")
	c.cancel()
	// TODO: wait for running tasks to finish / flush logs / close storage
	return nil
}

// SetConfigFile 动态设置配置文件
func (c *Collector) SetConfigFile(path string) error {
	cfg, err := config.LoadConfigFromFile(path)
	if err != nil {
		return err
	}
	c.config = cfg
	return nil
}

// SetLogger 日志配置替换
func (c *Collector) SetLogger(logger *zap.Logger) {
	c.logger = logger
}

// SetDebug 设置debug字段
func (c *Collector) SetDebug(debug bool) { c.debug = debug }
